using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Logging;

namespace RBAC.Read.Api.Utils
{
    /// <summary>
    /// 数据验证帮助类，用于检查导出数据的完整性和正确性
    /// </summary>
    public static class DataValidationHelper
    {
        /// <summary>
        /// 验证发货通知单数据的完整性
        /// </summary>
        /// <param name="data">要验证的数据</param>
        /// <param name="logger">日志记录器</param>
        /// <returns>验证结果</returns>
        public static DataValidationResult ValidateDeliveryNoticeData(IEnumerable<object> data, ILogger logger)
        {
            var result = new DataValidationResult();
            
            if (data == null || !data.Any())
            {
                result.IsValid = false;
                result.Errors.Add("数据为空");
                return result;
            }

            var dataList = data.ToList();
            result.TotalRecords = dataList.Count;
            
            logger.LogInformation("开始验证发货通知单数据，总记录数: {TotalRecords}", result.TotalRecords);

            // 检查每条记录的字段完整性
            for (int i = 0; i < dataList.Count; i++)
            {
                var record = dataList[i];
                var recordValidation = ValidateDeliveryNoticeRecord(record, i + 1, logger);
                
                if (!recordValidation.IsValid)
                {
                    result.Errors.AddRange(recordValidation.Errors);
                    result.InvalidRecords++;
                }
                else
                {
                    result.ValidRecords++;
                }
            }

            result.IsValid = result.Errors.Count == 0;
            
            logger.LogInformation("数据验证完成，有效记录: {ValidRecords}, 无效记录: {InvalidRecords}, 错误数: {ErrorCount}", 
                result.ValidRecords, result.InvalidRecords, result.Errors.Count);

            return result;
        }

        /// <summary>
        /// 验证单条发货通知单记录
        /// </summary>
        /// <param name="record">记录对象</param>
        /// <param name="recordIndex">记录索引</param>
        /// <param name="logger">日志记录器</param>
        /// <returns>验证结果</returns>
        private static RecordValidationResult ValidateDeliveryNoticeRecord(object record, int recordIndex, ILogger logger)
        {
            var result = new RecordValidationResult { RecordIndex = recordIndex };
            
            try
            {
                // 使用反射获取记录属性
                var properties = record.GetType().GetProperties();
                
                foreach (var property in properties)
                {
                    var value = property.GetValue(record);
                    var validationResult = ValidateField(property.Name, value, logger);
                    
                    if (!validationResult.IsValid)
                    {
                        result.Errors.Add($"字段 {property.Name}: {validationResult.ErrorMessage}");
                    }
                }
            }
            catch (Exception ex)
            {
                result.Errors.Add($"验证记录时发生异常: {ex.Message}");
                logger.LogError(ex, "验证记录 {RecordIndex} 时发生异常", recordIndex);
            }

            result.IsValid = result.Errors.Count == 0;
            return result;
        }

        /// <summary>
        /// 验证单个字段
        /// </summary>
        /// <param name="fieldName">字段名</param>
        /// <param name="value">字段值</param>
        /// <param name="logger">日志记录器</param>
        /// <returns>验证结果</returns>
        private static FieldValidationResult ValidateField(string fieldName, object value, ILogger logger)
        {
            var result = new FieldValidationResult { FieldName = fieldName };

            try
            {
                switch (fieldName)
                {
                    case "SalesOrderCode":
                        if (string.IsNullOrWhiteSpace(value?.ToString()))
                        {
                            result.IsValid = false;
                            result.ErrorMessage = "销售订单号不能为空";
                        }
                        break;

                    case "CustomerName":
                        if (string.IsNullOrWhiteSpace(value?.ToString()))
                        {
                            result.IsValid = false;
                            result.ErrorMessage = "客户名称不能为空";
                        }
                        break;

                    case "BillDate":
                        if (value is DateTime date)
                        {
                            if (date == default(DateTime) || date.Year <= 1900)
                            {
                                result.IsValid = false;
                                result.ErrorMessage = $"单据日期无效: {date:yyyy-MM-dd}";
                            }
                        }
                        else
                        {
                            result.IsValid = false;
                            result.ErrorMessage = "单据日期格式错误";
                        }
                        break;

                    case "DeliveryQuantity":
                        if (value is decimal quantity)
                        {
                            if (quantity < 0)
                            {
                                result.IsValid = false;
                                result.ErrorMessage = $"发货数量不能为负数: {quantity}";
                            }
                        }
                        break;

                    case "PieceCount":
                        if (value is int pieceCount)
                        {
                            if (pieceCount < 0)
                            {
                                result.IsValid = false;
                                result.ErrorMessage = $"件数不能为负数: {pieceCount}";
                            }
                        }
                        break;
                }

                if (result.IsValid)
                {
                    logger.LogDebug("字段 {FieldName} 验证通过，值: {Value}", fieldName, value);
                }
                else
                {
                    logger.LogWarning("字段 {FieldName} 验证失败: {ErrorMessage}", fieldName, result.ErrorMessage);
                }
            }
            catch (Exception ex)
            {
                result.IsValid = false;
                result.ErrorMessage = $"验证字段时发生异常: {ex.Message}";
                logger.LogError(ex, "验证字段 {FieldName} 时发生异常", fieldName);
            }

            return result;
        }

        /// <summary>
        /// 生成数据验证报告
        /// </summary>
        /// <param name="validationResult">验证结果</param>
        /// <returns>验证报告</returns>
        public static string GenerateValidationReport(DataValidationResult validationResult)
        {
            var report = new System.Text.StringBuilder();
            
            report.AppendLine("=== 发货通知单数据验证报告 ===");
            report.AppendLine($"验证时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
            report.AppendLine($"总记录数: {validationResult.TotalRecords}");
            report.AppendLine($"有效记录: {validationResult.ValidRecords}");
            report.AppendLine($"无效记录: {validationResult.InvalidRecords}");
            report.AppendLine($"验证结果: {(validationResult.IsValid ? "通过" : "失败")}");
            
            if (validationResult.Errors.Count > 0)
            {
                report.AppendLine();
                report.AppendLine("=== 错误详情 ===");
                foreach (var error in validationResult.Errors)
                {
                    report.AppendLine($"- {error}");
                }
            }
            
            return report.ToString();
        }
    }

    /// <summary>
    /// 数据验证结果
    /// </summary>
    public class DataValidationResult
    {
        public bool IsValid { get; set; } = true;
        public int TotalRecords { get; set; } = 0;
        public int ValidRecords { get; set; } = 0;
        public int InvalidRecords { get; set; } = 0;
        public List<string> Errors { get; set; } = new List<string>();
    }

    /// <summary>
    /// 记录验证结果
    /// </summary>
    public class RecordValidationResult
    {
        public bool IsValid { get; set; } = true;
        public int RecordIndex { get; set; } = 0;
        public List<string> Errors { get; set; } = new List<string>();
    }

    /// <summary>
    /// 字段验证结果
    /// </summary>
    public class FieldValidationResult
    {
        public bool IsValid { get; set; } = true;
        public string FieldName { get; set; } = string.Empty;
        public string ErrorMessage { get; set; } = string.Empty;
    }
} 